package model

import (
	"errors"
	"gitee.com/sansaniot/ssiot-gw-lib-comm/common/db"
	"gitee.com/sansaniot/ssiot-gw-lib-comm/common/utils/jsonutil"
	"gorm.io/datatypes"
	"gorm.io/gorm"
	"time"
)

type DpuConfig struct {
	ID        uint   `gorm:"primaryKey;"`
	DevSn     string `gorm:"uniqueIndex;type:varchar(50);comment:设备sn"`
	CommId    string `gorm:"index;type:varchar(50);comment:通讯链路唯一标识"`
	Config    datatypes.JSON
	CreatedAt time.Time
	UpdatedAt time.Time
}

// SaveBySn 更新配置
func (c *DpuConfig) SaveBySn() {
	commId := c.CommId
	config := c.Config
	result := c.Get()
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		db.Db.Create(c)
		return
	}
	db.Db.Model(c).Updates(DpuConfig{CommId: commId, Config: config})
}

// RemoveBySn 删除配置
func (c *DpuConfig) RemoveBySn() {
	db.Db.Delete(c, DpuConfig{DevSn: c.DevSn})
}

// Get 获取配置
func (c *DpuConfig) Get() (result *gorm.DB) {
	result = db.Db.Where(DpuConfig{DevSn: c.DevSn}).First(c)
	return
}

// GetByCommId 获取配置
func (c *DpuConfig) GetByCommId() (dpuConfig []byte) {
	// 查找通信链路上的所有设备
	devices := make([]DpuConfig, 0)
	result := db.Db.Where(DpuConfig{CommId: c.CommId}).Find(&devices)
	if result.Error != nil {
		return nil
	}

	// 组装通信链路上所有设备的config
	var config = make(map[string]interface{})
	for _, d := range devices {
		config[d.DevSn] = d.Config
	}

	return jsonutil.Map2Byte(config)
}
